package socks

import (
	"fmt"
	"net"
	"time"
)

type SocketClient interface {
	Open()  // 开始连接，打开会会自动连接
	Close() // 关闭连接
	GetConnection() SocketConnection
	Connected() bool // 判断是否连接
}

type socketClient struct {
	sockContext
	Connection *socketConnection
	connAddr   string
	isOpen     bool
}

func (c *socketClient) GetConnection() SocketConnection {
	return c.Connection
}

func (c *socketClient) doConnect() bool {
	ret := false
	conn, err := net.Dial("tcp", c.connAddr)
	if err == nil {
		ret = true
		c.Connection.setConn(conn)
		c.process_connection(c.Connection)
	}
	return ret
}
func (c *socketClient) Open() {
	if !c.isOpen {
		c.isOpen = true

		go func() {
			fmt.Println("开启自动连接")
			for c.isOpen {
				if !c.Connected() {
					if !c.doConnect() {
						fmt.Println("自动连接失败，暂停10秒！")
						time.Sleep(5 * time.Second)
					} else {
						fmt.Println("自动连接成功！")
					}
				}
				time.Sleep(time.Second)
			}
		}()
	}
}

func (c *socketClient) Close() {
	if c.isOpen {
		c.isOpen = false
		c.Connection.Disconnect()
	}
}

func (c *socketClient) Connected() bool {
	return !c.Connection.isClose.Load()
}

// override
func (c *socketClient) procConnect(sockConn *socketConnection) {
	c.MsgHandler.OnConnect(sockConn)
}

// override
func (c *socketClient) procDisconnect(sockConn *socketConnection) {
	c.MsgHandler.OnDisconnect(sockConn)
}

func NewSocketClient(addr string, avOpts SockOptions) SocketClient {
	avOpts.init() // 初始化参数

	client := &socketClient{
		Connection:  createSocketConnection(nil),
		sockContext: sockContext{SockOptions: avOpts},
		connAddr:    addr,
	}

	client.myConnHandler = client

	return client
}
